package org.jetlinks.pro.cassandra.metadata;

import org.hswebframework.ezorm.core.param.Term;
import org.hswebframework.ezorm.rdb.metadata.RDBColumnMetadata;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.PrepareSqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.SqlFragments;
import org.hswebframework.ezorm.rdb.operator.builder.fragments.term.AbstractTermFragmentBuilder;

import java.util.ArrayList;
import java.util.List;

class BetweenAndTermFragmentBuilder extends AbstractTermFragmentBuilder {

    private final boolean not;

    public BetweenAndTermFragmentBuilder(String termType, String name, boolean isNot) {
        super(termType, name);
        this.not = isNot;
    }

    @Override
    public SqlFragments createFragments(String columnFullName, RDBColumnMetadata column, Term term) {
        PrepareSqlFragments fragments = PrepareSqlFragments.of();

        List<Object> val = convertList(column, term);

        List<Object> values = new ArrayList<>(2);
        if (val.isEmpty()) {
            values.add(null);
            values.add(null);
        } else if (val.size() == 1) {
            values.add(val.get(0));
            values.add(val.get(0));
        } else {
            values.add(val.get(0));
            values.add(val.get(1));
        }
        if (not) {
            return fragments
                .addSql("(",columnFullName, "< ? or", columnFullName, ">= ? )")
                .addParameter(values);
        }
        return fragments
            .addSql(columnFullName, "> ? and", columnFullName, "<= ?")
            .addParameter(values);
    }
}